package com.heima.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ConsumerTest {
    public static void main(String[] args) {
        // 设置属性
        Properties props = new Properties();
        // 指定连接的kafka服务器的地址
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.137.136:9092");
        // 指定消费者的分组编号
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "group_1");
        // 构建kafka消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props, new StringDeserializer(), new StringDeserializer());
        // 定义kafka主题
        String topic = "sy_160_1";
        // 指定消费者订阅主题
        List<String> topics = new ArrayList<String>();
        topics.add(topic);
        consumer.subscribe(topics);
        // 调用消费者拉取消息
        while (true) {
            // Duration.ofSeconds(1) 每隔1秒拉取一次消息
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(1));
            // 遍历集合
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                String key = consumerRecord.key();
                String value = consumerRecord.value();
                System.out.println("接收到消息: key = " + key + ", value = " + value);
            }
        }
    }
}
